<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  

  
  <title>go[4]-测试 | Abel&#39;Blog</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="提高代码的质量，有两个路数：1.多测试；2.做代码review；如果能在代码放到外部去之前，做好单元测试，将会节省很多的时间（如果能把事情做好，减少很多处理bug的时间）。 单元测试（unit test）单元测试能自动化，只是手段，而非目的。避免形式主义。需要持之以恒。想要习惯去做测试还是需要将测试的手段非常熟练，而且易用才能解开。 编写单元测试是对即将实现的算法做复核预演。 测试代码需要在当前包">
<meta property="og:type" content="article">
<meta property="og:title" content="go[4]-测试">
<meta property="og:url" content="http://example.com/2020/11/18/2020/2020-11-18-go[5]-%E6%B5%8B%E8%AF%95/index.html">
<meta property="og:site_name" content="Abel&#39;Blog">
<meta property="og:description" content="提高代码的质量，有两个路数：1.多测试；2.做代码review；如果能在代码放到外部去之前，做好单元测试，将会节省很多的时间（如果能把事情做好，减少很多处理bug的时间）。 单元测试（unit test）单元测试能自动化，只是手段，而非目的。避免形式主义。需要持之以恒。想要习惯去做测试还是需要将测试的手段非常熟练，而且易用才能解开。 编写单元测试是对即将实现的算法做复核预演。 测试代码需要在当前包">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2020-11-17T16:00:00.000Z">
<meta property="article:modified_time" content="2021-07-28T09:13:04.793Z">
<meta property="article:author" content="Abel Sean">
<meta property="article:tag" content="golang">
<meta name="twitter:card" content="summary">
  
    <link rel="alternate" href="/atom.xml" title="Abel&#39;Blog" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  
<link rel="stylesheet" href="/css/style.css">

<meta name="generator" content="Hexo 5.4.0"></head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">Abel&#39;Blog</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://example.com"></form>
      </div>
    </div>
  </div>
</header>
      <div class="outer">
        <section id="main"><article id="post-2020/2020-11-18-go[5]-测试" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2020/11/18/2020/2020-11-18-go%5B5%5D-%E6%B5%8B%E8%AF%95/" class="article-date">
  <time datetime="2020-11-17T16:00:00.000Z" itemprop="datePublished">2020-11-18</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      go[4]-测试
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <p>提高代码的质量，有两个路数：1.多测试；2.做代码review；如果能在代码放到外部去之前，做好单元测试，将会节省很多的时间（如果能把事情做好，减少很多处理bug的时间）。</p>
<h3 id="单元测试（unit-test）"><a href="#单元测试（unit-test）" class="headerlink" title="单元测试（unit test）"></a>单元测试（unit test）</h3><p>单元测试能自动化，只是手段，而非目的。避免形式主义。需要持之以恒。想要习惯去做测试还是需要将测试的手段非常熟练，而且易用才能解开。</p>
<p>编写单元测试是对即将实现的算法做复核预演。</p>
<p>测试代码需要在当前包以_test.go结束的文件。</p>
<p>测试函数以Test为名字前缀。</p>
<p>测试命令go test忽略_,.开头的测试文件。</p>
<p>正常编译的时候，会忽略掉测试文件。</p>
<p>main_test.go</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"><span class="keyword">import</span>(</span><br><span class="line">   <span class="string">&quot;testing&quot;</span></span><br><span class="line">)</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">add</span><span class="params">(x,y <span class="keyword">int</span>)</span> <span class="title">int</span></span> &#123;</span><br><span class="line">   <span class="keyword">return</span> x+y</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">TestAdd</span><span class="params">(t *testing.T)</span></span>&#123;</span><br><span class="line">    <span class="keyword">if</span> add(<span class="number">1</span>,<span class="number">2</span>) != <span class="number">3</span> &#123;</span><br><span class="line">        t.FailNow()</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable">$go</span> <span class="built_in">test</span> -v</span><br><span class="line">[cq@localhost test_case]$ go <span class="built_in">test</span> -v</span><br><span class="line">=== RUN   TestAdd</span><br><span class="line">--- PASS: TestAdd (0.00s)</span><br><span class="line">PASS</span><br><span class="line">ok  	test_case	0.002s</span><br></pre></td></tr></table></figure>

<p>遍历子包测试用例。</p>
<p>testing.T提供的函数</p>
<table>
<thead>
<tr>
<th>方法</th>
<th>说明</th>
<th>相关</th>
</tr>
</thead>
<tbody><tr>
<td>Fail</td>
<td>失败：继续执行当前测试用例</td>
<td></td>
</tr>
<tr>
<td>FailNow</td>
<td>失败：终止当前测试</td>
<td>Failed</td>
</tr>
<tr>
<td>SkipNow</td>
<td>跳过：停止执行当前测试函数</td>
<td>Skip,Skipf,Skipped</td>
</tr>
<tr>
<td>Log</td>
<td>输出日志，仅在失败或者-v时候输出</td>
<td>Logf</td>
</tr>
<tr>
<td>Parallel</td>
<td>与有相同设置的测试函数并行执行（一般会设置两个以上测试用例，否则就无用了）</td>
<td></td>
</tr>
<tr>
<td>Error</td>
<td>Fail+Log</td>
<td>Errorf</td>
</tr>
<tr>
<td>Fatal</td>
<td>FailNow+Log</td>
<td>Fatalf</td>
</tr>
</tbody></table>
<p>测试命令常用的参数列表</p>
<table>
<thead>
<tr>
<th>参数</th>
<th>说明</th>
<th>实例</th>
</tr>
</thead>
<tbody><tr>
<td>-args</td>
<td>命令行参数</td>
<td></td>
</tr>
<tr>
<td>-v</td>
<td>输出详细信息verbose</td>
<td></td>
</tr>
<tr>
<td>-parallel</td>
<td>并行执行多个测试用例</td>
<td></td>
</tr>
<tr>
<td>-run</td>
<td>运行指定测试用例，能支持正则表达式</td>
<td></td>
</tr>
<tr>
<td>-timeout</td>
<td>全部测试超时将会调用panic默认10ms</td>
<td>-timeout 1m30s</td>
</tr>
<tr>
<td>-count</td>
<td>重复测试次数</td>
<td></td>
</tr>
</tbody></table>
<h4 id="table-driven"><a href="#table-driven" class="headerlink" title="table driven"></a>table driven</h4><p>使用table将测试参数都准备好，然后推进测试。测试数据和测试逻辑分离，有利于维护。</p>
<h4 id="test-main"><a href="#test-main" class="headerlink" title="test main"></a>test main</h4><p>如果定义了TestMain函数，go test将会执行这个函数，而不是每个具体的测试用例，这样就能把测试的setup/teardown机制用起来。比如测试一些db操作，需要先构造一个db的链接之类的，就可以使用这种模式。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">TestMain</span><span class="params">(m *testing.M)</span></span> &#123;</span><br><span class="line">    code :=m.Run()</span><br><span class="line">    os.Exit(code)</span><br></pre></td></tr></table></figure>

<h4 id="example"><a href="#example" class="headerlink" title="example"></a>example</h4><p>例代码是用于给GoDoc生成帮助文档。对比stdout结果和内部Output注释是否一致来判断是否成功</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">ExampleAdd</span><span class="params">()</span></span> &#123;</span><br><span class="line">   fmt.Println(add(<span class="number">1</span>,<span class="number">2</span>))</span><br><span class="line">   fmt.Println(add(<span class="number">2</span>,<span class="number">2</span>))</span><br><span class="line">   <span class="comment">// Output:</span></span><br><span class="line">   <span class="comment">// 3</span></span><br><span class="line">   <span class="comment">// 4</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="性能测试"><a href="#性能测试" class="headerlink" title="性能测试"></a>性能测试</h3><p>文件名也是使用的 _test.go结束的。函数名称需要使用Benchmark为前缀 </p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">add</span><span class="params">(x,y <span class="keyword">int</span>)</span> <span class="title">int</span></span> &#123;</span><br><span class="line">    <span class="keyword">return</span> x+y</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">BenchmarkAdd</span><span class="params">(b *testing.B)</span></span> &#123;</span><br><span class="line">      <span class="keyword">for</span> i :=<span class="number">0</span>;i&lt;b.N;i++ &#123;</span><br><span class="line">        _ := add(<span class="number">1</span>,<span class="number">2</span>)</span><br><span class="line">     &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">go</span> test -bench</span><br></pre></td></tr></table></figure>

<p>希望忽略掉全部的单元测试，可以使用run=NONE。默认就是并发测试，可以通过-cpu参数设定多个并发限制。</p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://example.com/2020/11/18/2020/2020-11-18-go[5]-%E6%B5%8B%E8%AF%95/" data-id="ckrn3an77000z20xw8ngj9f1x" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/golang/" rel="tag">golang</a></li></ul>

    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2020/11/18/2020/2020-11-18-go%5B4%5D-gogrutines/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          go[4]-goroutine
        
      </div>
    </a>
  
  
    <a href="/2020/11/16/2020/2020-11-14-golang-pprof/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">golang-pprof性能分析工具</div>
    </a>
  
</nav>

  
</article>

</section>
        
          <aside id="sidebar">
  
    

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tags</h3>
    <div class="widget">
      <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/tags/3D/" rel="tag">3D</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/AI/" rel="tag">AI</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/C/" rel="tag">C++</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Game/" rel="tag">Game</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Go/" rel="tag">Go</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Linux/" rel="tag">Linux</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Math/" rel="tag">Math</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Server/" rel="tag">Server</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Unreal-Engine4/" rel="tag">Unreal Engine4</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/git/" rel="tag">git</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/golang/" rel="tag">golang</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/guitar/" rel="tag">guitar</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/node-js/" rel="tag">node.js</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/protobuf/" rel="tag">protobuf</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/python/" rel="tag">python</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/recast/" rel="tag">recast</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/redis/" rel="tag">redis</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/type/" rel="tag">type</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/vscode/" rel="tag">vscode</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E8%BF%90%E7%BB%B4/" rel="tag">运维</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tag Cloud</h3>
    <div class="widget tagcloud">
      <a href="/tags/3D/" style="font-size: 10px;">3D</a> <a href="/tags/AI/" style="font-size: 11.67px;">AI</a> <a href="/tags/C/" style="font-size: 15px;">C++</a> <a href="/tags/Game/" style="font-size: 18.33px;">Game</a> <a href="/tags/Go/" style="font-size: 13.33px;">Go</a> <a href="/tags/Linux/" style="font-size: 13.33px;">Linux</a> <a href="/tags/Math/" style="font-size: 11.67px;">Math</a> <a href="/tags/Server/" style="font-size: 16.67px;">Server</a> <a href="/tags/Unreal-Engine4/" style="font-size: 10px;">Unreal Engine4</a> <a href="/tags/git/" style="font-size: 10px;">git</a> <a href="/tags/golang/" style="font-size: 20px;">golang</a> <a href="/tags/guitar/" style="font-size: 10px;">guitar</a> <a href="/tags/node-js/" style="font-size: 10px;">node.js</a> <a href="/tags/protobuf/" style="font-size: 10px;">protobuf</a> <a href="/tags/python/" style="font-size: 10px;">python</a> <a href="/tags/recast/" style="font-size: 11.67px;">recast</a> <a href="/tags/redis/" style="font-size: 10px;">redis</a> <a href="/tags/type/" style="font-size: 10px;">type</a> <a href="/tags/vscode/" style="font-size: 10px;">vscode</a> <a href="/tags/%E8%BF%90%E7%BB%B4/" style="font-size: 16.67px;">运维</a>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/07/">July 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/06/">June 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/04/">April 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/03/">March 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/01/">January 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/12/">December 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/11/">November 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/03/">March 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/11/">November 2018</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2021/07/19/2021/2021-07-19-etcd-learn/">go-etcd阅读笔记</a>
          </li>
        
          <li>
            <a href="/2021/07/19/2021/2021-07-19-socketop-learn/">REUSEPORT-REUSEADDR-学习</a>
          </li>
        
          <li>
            <a href="/2021/06/22/2021/2021-06-22-go-ethereum-learn/">go-ethereum阅读笔记</a>
          </li>
        
          <li>
            <a href="/2021/06/21/2021/2021-06-21-server%E6%B5%8B%E8%AF%95%E5%B7%A5%E5%85%B7/">server测试工具</a>
          </li>
        
          <li>
            <a href="/2021/06/09/2021/2021-06-09-pprof-doc/">go-pprof</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2021 Abel Sean<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>
    </div>
    <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>


  
<link rel="stylesheet" href="/fancybox/jquery.fancybox.css">

  
<script src="/fancybox/jquery.fancybox.pack.js"></script>




<script src="/js/script.js"></script>




  </div>
</body>
</html>